import Vue from 'vue'
import Vuex from 'vuex'
import Menu from '@/api/menuAPI.js'
import { staticRoute, asyncRoute, exceptionRoute } from '@/router'
import router from '@/router'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    menus: [],
    dynamicRoute: [],
    resultRoute: [],
    btnPermission: [],
  },
  getters: {},
  actions: {
    set_token({ commit }, payload) {
      commit('SET_TOKEN', payload)
    },
    async set_menu({ commit }, payload) {
      //2.查询当前用户所拥有的角色并存入vuex
      let res1 = await Menu.queryPermissionByUser()
      let { code, msg, data } = res1.data
      commit('SET_MENU', data)

      // 第一种方式
      // //3.根据当前查询到的菜单信息动态生成路由
      // let dynamicRoute = parseRouter(data, [])
      // commit('SET_DYNAMICROUTE', dynamicRoute)

      // 第二种方式
      //3.发送请求 查询当前用户所拥有的路由组件访问信息
      let res2 = await Menu.queryRouteByUser()
      let routerArr = res2.data.data
      let dynamicRoute = equalsRoutes(asyncRoute, routerArr)
      commit('SET_DYNAMICROUTE', dynamicRoute)

      //4.组合路由生成一个最终的结果路由
      staticRoute.forEach((item) => {
        if (item.path === '/home') {
          item.children = dynamicRoute
        }
      })

      commit('SET_RESULTROUTE', [...staticRoute, ...exceptionRoute])
    },
    set_btnPermission({ commit }, payload) {
      commit('SET_BTNPERMISSION', payload)
    },
  },
  mutations: {
    SET_TOKEN(state, payload) {
      // 1.将token存入sessionStorage
      // sessionStorage.setItem('token', payload)
      state.token = payload
    },
    SET_MENU(state, payload) {
      state.menus = payload
    },
    SET_DYNAMICROUTE(state, payload) {
      state.dynamicRoute = payload
    },
    SET_RESULTROUTE(state, payload) {
      state.resultRoute = payload

      //最后一步：把最终的结果路由 添加给 路由器
      //router.addRoutes(payload);
      state.resultRoute.forEach((item) => {
        router.addRoute(item)
      })
    },
    SET_BTNPERMISSION(state, payload) {
      state.btnPermission = payload
    },
  },
  modules: {},
})

//定义封装异步路由的函数
function parseRouter(menus, arr) {
  //console.log(arr);
  menus.forEach((item) => {
    //代表有子菜单，他是父级菜单 不需要加入到路由规则中
    if (item.children && item.children.length > 0) {
      parseRouter(item.children, arr)
    } else {
      let obj = {}
      obj.path = item.path
      //obj.component = () => import(`${item.component}`);
      obj.component = (resolve) =>
        require(['@/views/' + item.component], resolve)
      obj.meta = item.name
      obj.children = []
      arr.push(obj)
    }
  })
  return arr
}

/*
  asyncRoutes:表示我们自己根据项目定义的全局路由规则
  routes:表示查询出的当前登录用户所具有的权限数组
*/
//把查询到的用户所具有的路由与全局路由规则做对比 筛选出 用户应该具有的路由规则
function equalsRoutes(asyncRoutes, routes) {
  return asyncRoutes.filter((item) => {
    //如果路由中包含item.name
    if (routes.includes(item.name)) {
      //再判断该路由中是否含有子级路由，如果含有子级路由，也要比对
      if (item.children && item.children.length > 0) {
        item.children = equalsRoutes(item.children, routes)
      }
      return true
    }
  })
}
